package com.woniuxy;

import com.woniuxy.config.RedisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Configuration
public class RedisLockConfig {
    @Autowired
    private RedisConfig redisConfig;

    public boolean lock(String key){
        long start = System.currentTimeMillis();
        Boolean b = redisConfig.opsForValue().setIfAbsent(key, UUID.randomUUID().toString(), 20, TimeUnit.SECONDS);
        while(!b){
            b = redisConfig.opsForValue().setIfAbsent(key, UUID.randomUUID().toString(), 20, TimeUnit.SECONDS);
            if(System.currentTimeMillis()-start>=3000){
                return false;
            }
        }
        return b;
    }
    public void unlock(String key){
        redisConfig.delete(key);
    }
}
